<template>
  <div class="message-search">
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        :placeholder="placeholder"
        class="search-input"
        clearable
        @clear="handleClear"
        @keyup.enter="handleSearch"
        @input="handleInput"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
        <template #append>
          <el-button @click="showAdvancedSearch = !showAdvancedSearch">
            {{ showAdvancedSearch ? '收起' : '展开' }}高级搜索
            <el-icon>
              <component :is="showAdvancedSearch ? 'ArrowUp' : 'ArrowDown'" />
            </el-icon>
          </el-button>
        </template>
      </el-input>

      <!-- 搜索建议 -->
      <div v-if="showSuggestions && suggestions.length > 0" class="search-suggestions">
        <div
          v-for="(item, index) in suggestions"
          :key="index"
          class="suggestion-item"
          :class="{ active: currentSuggestionIndex === index }"
          @click="handleSuggestionClick(item)"
          @mouseenter="currentSuggestionIndex = index"
        >
          <el-icon><Search /></el-icon>
          <span class="suggestion-text">{{ item.text }}</span>
          <span class="suggestion-type">{{ item.type }}</span>
        </div>
      </div>

      <!-- 搜索历史 -->
      <div v-if="showHistory && searchHistory.length > 0" class="search-history">
        <div class="history-header">
          <span>搜索历史</span>
          <el-button type="primary" link @click="clearHistory">
            <el-icon><Delete /></el-icon>清空历史
          </el-button>
        </div>
        <div class="history-list">
          <div
            v-for="(item, index) in searchHistory"
            :key="index"
            class="history-item"
            @click="handleHistoryClick(item)"
          >
            <el-icon><Clock /></el-icon>
            <span class="history-text">{{ item }}</span>
            <el-button
              type="primary"
              link
              class="delete-btn"
              @click.stop="removeHistoryItem(index)"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 高级搜索表单 -->
    <el-collapse-transition>
      <div v-show="showAdvancedSearch" class="advanced-search">
        <el-form
          ref="advancedFormRef"
          :model="advancedForm"
          label-width="100px"
          class="search-form"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="消息类型">
                <el-select
                  v-model="advancedForm.types"
                  multiple
                  collapse-tags
                  placeholder="请选择消息类型"
                >
                  <el-option
                    v-for="type in messageTypes"
                    :key="type.value"
                    :label="type.label"
                    :value="type.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="处理状态">
                <el-select
                  v-model="advancedForm.status"
                  multiple
                  collapse-tags
                  placeholder="请选择处理状态"
                >
                  <el-option
                    v-for="status in processStatus"
                    :key="status.value"
                    :label="status.label"
                    :value="status.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="advancedForm.timeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="创建人">
                <el-select
                  v-model="advancedForm.creator"
                  filterable
                  remote
                  :remote-method="searchUsers"
                  :loading="userSearchLoading"
                  placeholder="请选择创建人"
                >
                  <el-option
                    v-for="user in userOptions"
                    :key="user.id"
                    :label="user.name"
                    :value="user.id"
                  >
                    <span>{{ user.name }}</span>
                    <span class="user-department">{{ user.department }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="处理人">
                <el-select
                  v-model="advancedForm.handler"
                  filterable
                  remote
                  :remote-method="searchUsers"
                  :loading="userSearchLoading"
                  placeholder="请选择处理人"
                >
                  <el-option
                    v-for="user in userOptions"
                    :key="user.id"
                    :label="user.name"
                    :value="user.id"
                  >
                    <span>{{ user.name }}</span>
                    <span class="user-department">{{ user.department }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="标签">
                <el-select
                  v-model="advancedForm.tags"
                  multiple
                  collapse-tags
                  filterable
                  placeholder="请选择标签"
                >
                  <el-option
                    v-for="tag in tagOptions"
                    :key="tag.id"
                    :label="tag.name"
                    :value="tag.id"
                  >
                    <el-tag
                      :type="tag.type"
                      :effect="tag.effect"
                      size="small"
                    >
                      {{ tag.name }}
                    </el-tag>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="search-buttons">
              <el-button @click="resetAdvancedSearch">重置</el-button>
              <el-button type="primary" @click="handleAdvancedSearch">搜索</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-collapse-transition>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue'
import { Search, ArrowUp, ArrowDown, Delete, Clock, Close } from '@element-plus/icons-vue'
import { searchUsers, getMessageTypes, getMessageTags } from '@/api/message'
import { useMessageStore } from '@/stores/message'
import { storeToRefs } from 'pinia'

const props = defineProps({
  placeholder: {
    type: String,
    default: '搜索消息标题/内容'
  },
  immediate: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['search', 'update:modelValue'])

// 状态管理
const messageStore = useMessageStore()
const { searchHistory } = storeToRefs(messageStore)

// 搜索相关
const searchQuery = ref('')
const showAdvancedSearch = ref(false)
const showSuggestions = ref(false)
const showHistory = ref(false)
const currentSuggestionIndex = ref(-1)
const userSearchLoading = ref(false)
const userOptions = ref([])

// 高级搜索表单
const advancedFormRef = ref(null)
const advancedForm = reactive({
  types: [],
  status: [],
  timeRange: [],
  creator: '',
  handler: '',
  tags: []
})

// 消息类型
const messageTypes = ref([])
const processStatus = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'rejected', label: '已驳回' },
  { value: 'cancelled', label: '已取消' }
]

// 标签选项
const tagOptions = ref([])

// 搜索建议
const suggestions = ref([])
const suggestionTimer = ref(null)

// 监听搜索框输入
watch(searchQuery, (val) => {
  if (suggestionTimer.value) {
    clearTimeout(suggestionTimer.value)
  }
  
  if (val) {
    suggestionTimer.value = setTimeout(() => {
      generateSuggestions(val)
    }, 300)
  } else {
    suggestions.value = []
    showSuggestions.value = false
  }
})

// 初始化数据
onMounted(async () => {
  await Promise.all([
    fetchMessageTypes(),
    fetchMessageTags()
  ])
  
  if (props.immediate) {
    handleSearch()
  }
})

// 清理定时器
onUnmounted(() => {
  if (suggestionTimer.value) {
    clearTimeout(suggestionTimer.value)
  }
})

// 获取消息类型
const fetchMessageTypes = async () => {
  try {
    const res = await getMessageTypes()
    messageTypes.value = res.data
  } catch (error) {
    console.error('获取消息类型失败:', error)
  }
}

// 获取消息标签
const fetchMessageTags = async () => {
  try {
    const res = await getMessageTags()
    tagOptions.value = res.data
  } catch (error) {
    console.error('获取消息标签失败:', error)
  }
}

// 生成搜索建议
const generateSuggestions = (query) => {
  const suggestions = []
  
  // 标题建议
  suggestions.push({
    type: '标题',
    text: query
  })
  
  // 内容建议
  if (query.length > 2) {
    suggestions.push({
      type: '内容',
      text: query
    })
  }
  
  // 类型建议
  messageTypes.value.forEach(type => {
    if (type.label.includes(query)) {
      suggestions.push({
        type: '类型',
        text: type.label
      })
    }
  })
  
  // 标签建议
  tagOptions.value.forEach(tag => {
    if (tag.name.includes(query)) {
      suggestions.push({
        type: '标签',
        text: tag.name
      })
    }
  })
  
  suggestions.value = suggestions
  showSuggestions.value = true
}

// 处理搜索建议点击
const handleSuggestionClick = (item) => {
  searchQuery.value = item.text
  showSuggestions.value = false
  handleSearch()
}

// 处理搜索历史点击
const handleHistoryClick = (item) => {
  searchQuery.value = item
  showHistory.value = false
  handleSearch()
}

// 删除搜索历史项
const removeHistoryItem = (index) => {
  messageStore.removeSearchHistory(index)
}

// 清空搜索历史
const clearHistory = () => {
  messageStore.clearSearchHistory()
}

// 搜索用户
const searchUsers = async (query) => {
  if (query) {
    userSearchLoading.value = true
    try {
      const res = await searchUsers({ query })
      userOptions.value = res.data
    } catch (error) {
      console.error('搜索用户失败:', error)
    } finally {
      userSearchLoading.value = false
    }
  } else {
    userOptions.value = []
  }
}

// 处理搜索
const handleSearch = () => {
  const params = {
    query: searchQuery.value,
    ...advancedForm,
    startTime: advancedForm.timeRange?.[0],
    endTime: advancedForm.timeRange?.[1]
  }
  
  // 保存搜索历史
  if (searchQuery.value) {
    messageStore.addSearchHistory(searchQuery.value)
  }
  
  emit('search', params)
  showSuggestions.value = false
  showHistory.value = false
}

// 处理高级搜索
const handleAdvancedSearch = () => {
  handleSearch()
}

// 重置高级搜索
const resetAdvancedSearch = () => {
  if (advancedFormRef.value) {
    advancedFormRef.value.resetFields()
  }
  handleSearch()
}

// 处理清空
const handleClear = () => {
  searchQuery.value = ''
  showSuggestions.value = false
  handleSearch()
}

// 处理输入
const handleInput = () => {
  showHistory.value = !searchQuery.value
}

// 键盘导航
const handleKeyDown = (e) => {
  if (!showSuggestions.value) return
  
  switch (e.key) {
    case 'ArrowDown':
      e.preventDefault()
      currentSuggestionIndex.value = Math.min(
        currentSuggestionIndex.value + 1,
        suggestions.value.length - 1
      )
      break
    case 'ArrowUp':
      e.preventDefault()
      currentSuggestionIndex.value = Math.max(currentSuggestionIndex.value - 1, 0)
      break
    case 'Enter':
      e.preventDefault()
      if (currentSuggestionIndex.value >= 0) {
        handleSuggestionClick(suggestions.value[currentSuggestionIndex.value])
      } else {
        handleSearch()
      }
      break
    case 'Escape':
      showSuggestions.value = false
      break
  }
}

// 点击外部关闭建议和历史
const handleClickOutside = (e) => {
  const searchBar = document.querySelector('.message-search')
  if (searchBar && !searchBar.contains(e.target)) {
    showSuggestions.value = false
    showHistory.value = false
  }
}

// 添加事件监听
onMounted(() => {
  document.addEventListener('keydown', handleKeyDown)
  document.addEventListener('click', handleClickOutside)
})

// 移除事件监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style lang="scss" scoped>
.message-search {
  position: relative;
  
  .search-bar {
    position: relative;
    
    .search-input {
      width: 100%;
      
      :deep(.el-input-group__append) {
        padding: 0;
        
        .el-button {
          margin: 0;
          border: none;
          height: 100%;
          padding: 0 15px;
        }
      }
    }
    
    .search-suggestions {
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
      background: #fff;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      z-index: 1000;
      margin-top: 4px;
      
      .suggestion-item {
        display: flex;
        align-items: center;
        padding: 8px 16px;
        cursor: pointer;
        
        &:hover,
        &.active {
          background-color: #f5f7fa;
        }
        
        .el-icon {
          margin-right: 8px;
          color: #909399;
        }
        
        .suggestion-text {
          flex: 1;
        }
        
        .suggestion-type {
          color: #909399;
          font-size: 12px;
          margin-left: 8px;
        }
      }
    }
    
    .search-history {
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
      background: #fff;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      z-index: 1000;
      margin-top: 4px;
      
      .history-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 16px;
        border-bottom: 1px solid #ebeef5;
        
        span {
          color: #909399;
          font-size: 14px;
        }
      }
      
      .history-list {
        max-height: 300px;
        overflow-y: auto;
        
        .history-item {
          display: flex;
          align-items: center;
          padding: 8px 16px;
          cursor: pointer;
          
          &:hover {
            background-color: #f5f7fa;
            
            .delete-btn {
              display: block;
            }
          }
          
          .el-icon {
            margin-right: 8px;
            color: #909399;
          }
          
          .history-text {
            flex: 1;
          }
          
          .delete-btn {
            display: none;
            padding: 0;
            margin-left: 8px;
          }
        }
      }
    }
  }
  
  .advanced-search {
    margin-top: 16px;
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 4px;
    
    .search-form {
      .search-buttons {
        display: flex;
        justify-content: center;
        gap: 16px;
        margin-top: 16px;
      }
    }
  }
}

.user-department {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}
</style> 